<?php

/**
 * 登陆控制器
 * @access public
 * @author jackson_xu@outlook.com
 */

namespace Home\Controller;

use Org\Util\Rbac;
use Think\Controller;

class LoginController extends Controller {

    //测试OA系统中的计划管理通过curl传参打开页面
    public function index() {
        $user_id = I('user_id');
        $info = M('user')->where('user_id="' . $user_id . '"')->find();
        if ($info) {
            session('user_id', $user_id);
            $return = array('status' => 1, 'url' => 'http://221.226.30.122:88');
        } else {
            $return = array('status' => 0);
        }
        $this->ajaxReturn($return);
    }

    public function login() {
        if (IS_AJAX) {
            $data = I('post.');
            /* 记住密码  update zyh 2018/8/1 (新系统登录没有此功能)
              if ($data['online'] == 1) {
              cookie("username", trim($data['username']), time() + 3600 * 24 * 365);
              cookie("password", trim($data['password']), time() + 3600 * 24 * 365);
              } else {
              setcookie('username', '', 0);
              setcookie('password', '', 0);
              } */
//            cookie("username", trim($data['username']), time() + 3600 * 24 * 365);

            $map1['user_id'] = trim($data['username']);
            $row = M('user')->where($map1)->find();
            if (!$row) {
                $map2['byname'] = trim($data['username']);
                $row = M('user')->where($map2)->find();
            }

            if (!$row) {
                $return['info'] = '该用户不存在';
                $return['icon'] = 5;
                $return['status'] = 0;
            } else {
                //验证密码
                if (crypt(trim($data['password']), $row['password']) != $row['password']) {
                    $return['info'] = '用户名或密码不正确';
                    $return['icon'] = 5;
                    $return['status'] = 0;
                } else {
                    //获取上次登录时间
                    $lastTime = M('user_login')->where('user_id="' . $row['user_id'] . '"')->order('login_time desc')->limit(1)->getField('login_time');
                    $timeData['last_visit_time'] = date('Y-m-d H:i:s', $lastTime);
                    $timeData['is_online'] = 1;
                    M('user')->where('user_id="' . $row['user_id'] . '"')->save($timeData);
                    //修改登录时间
                    $loginData['login_time'] = time();
                    $loginData['type'] = 0;
                    $loginData['user_id'] = $row['user_id'];
                    M('user_login')->add($loginData);

                    session('user_id', $row['user_id']);
                    session('user_name', $row['user_name']);
                    session('dept_id', $row['dept_id']);
                    session('dept_id_other', $row['dept_id_other']);
                    session('user_priv', $row['user_priv']);
                    session('user_priv_other', $row['user_priv_other']);
                    $return['url'] = U('Index/index');
                }
            }

            //获取当前用户菜单
            $user = M('user')->field('user_id,user_name,user_priv,user_priv_other')->where('user_id="' . session('user_id') . '"')->find();
            $privs = $user['user_priv'] . ',' . $user['user_priv_other'];
            //获权限menu_id
            $rMap['user_priv'] = array('in', explode(',', rtrim($privs)));
            $menus = M('user_priv')->where($rMap)->getField('menu_id', true);
            if (!is_array($menus)) {
                $menus[] = $menus;
            }
            $menus = implode(',', $menus);
            $bmap['id'] = array('in', array_unique(explode(',', $menus)));
            $bmap['is_show'] = 1;

            //重组数据
            $datas = M('backmenu')->where($bmap)->order('sort')->select();
            $userMenus = [];
            foreach ($datas as $key => $row) {
                if ($row['pid'] == 0) {
                    $userMenus[] = $row;
                }
            }
            foreach ($userMenus as $key => $row) {
                foreach ($datas as $k => $v) {
                    if ($row['id'] == $v['pid']) {
                        $userMenus[$key]['child'][] = $v;
                    }
                }
            }
            session('userMenus', $userMenus);

            $this->ajaxReturn($return);
        }

//        $this->username = cookie('username');
//        $this->password = cookie('password');

        $this->display();
    }

    //验证码生成
    public function verify() {
        ob_clean();
        $config = array(
            'fontSize' => 16, // 验证码字体大小   
            'length' => 4, // 验证码位数    
            'useNoise' => false, // 关闭验证码杂点
            'imageW' => '110px',
        );
        $Verify = new \Think\Verify($config);
        $Verify->codeSet = '123456789';
        $Verify->entry();
    }

    //检测验证码是否正确
    function check_verify($code, $id = '') {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    //ajax验证验证码
    function checkCode() {
        $code = I("code");
        $verfity = $this->check_verify($code, '');
        if ($verfity) {
            $this->ajaxReturn('true');
        } else {
            $this->ajaxReturn('false');
        }
    }

    //验证账号是否存在
    function ajaxUserName() {
        $map['username'] = I("post.email");
        $res = M("company_user")->where($map)->find();
        if ($res) {
            $this->ajaxReturn("false");
        } else {
            $this->ajaxReturn("true");
        }
    }

    public function emailForgotPassword() {
        $map['username'] = I("post.email");
        $map['id'] = M("user")->where($map)->getField("id");
        if ($map['id']) {
            $newPwd = getRandomString(6);
            $map['password'] = md5($newPwd);
            M("user")->save($map);
            //参数: 参数1---目标邮箱, 参数2----邮件标题,参数三--邮件正文,参数四---发件人名称
            $res = sendEmail($map['username'], "会员新密码", "我们从 美栎 收到您请求新的密码，建议您在使用新密码登入后立即变更此密码，并妥善保存...您的新密码：" . $newPwd, "美栎");

            if ($res) {
                $this->ajaxReturn("true");
            } else {
                $this->ajaxReturn("no_email");
            }
        } else {
            $this->ajaxReturn("false");
        }
    }

    //公司注册时，首次进入需完善公司资料
    public function companyInfos() {
        if (IS_POST) {
            $data = I("post.");
            $data['is_perfect'] = 1;
            $where['id'] = session("oa_company_id");
            $res = M("company")->where($where)->save($data);
            if ($res !== false) {
                session("oa_company_is_perfect", 1);
                $this->redirect("Manage/Index/index");
            } else {
                $this->error("更新失败,请联系管理员");
            }
        } else {
            $where['id'] = session("oa_company_id");
            $info = M("company")->where($where)->find();
            $addr = M("area")->where("pid=0")->select();
            $this->addr = $addr;
            $this->info = $info;
            $this->title = "完善信息";
            $this->display();
        }
    }

    public function ajaxArea() {
        $area_model = M("area");
        $province_id['pid'] = I("post.id");
        if ($province_id['pid'] == "#")
            $this->ajaxReturn(false);
        $res = $area_model->where($province_id)->field("id,name")->select();
        $this->ajaxReturn($res);
    }

    public function logout() {
        $data['is_online'] = 0;
        $data['leave_time'] = date('Y-m-d H:i:s');
        $map['user_id'] = session('user_id');
        $res = M('user')->where($map)->save($data);
        session(null);
        if ($res !== false) {
            if (!session('user_id')) {
                $this->redirect('Login/login');
            }
        }
    }

}
